<template>
  <div class="contact-page">
    <!-- 复用导航栏组件 -->
    <HeaderNav />
    
    <!-- 页面标题区 -->
    <section class="page-banner">
      <div class="banner-content">
        <h1 class="page-title">{{ t('contact.pageTitle') }}</h1>
        <div class="page-breadcrumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item><router-link to="/">{{ t('common.home') }}</router-link></el-breadcrumb-item>
            <el-breadcrumb-item>{{ t('contact.pageTitle') }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </div>
    </section>
    
    <!-- 主内容区 -->
    <main class="main-content">
      <!-- 模块1：公司联系方式 -->
      <section class="contact-info">
        <div class="container">
          <div class="info-cards">
            <div class="info-card" v-for="(item, index) in contactInfo" :key="index" data-aos="fade-up" :data-aos-delay="index * 100">
              <div class="info-icon">
                <i class="iconfont" :class="item.icon"></i>
              </div>
              <div class="info-content">
                <div class="info-title">{{ item.title }}</div>
                <div class="info-value">{{ item.value }}</div>
              </div>
            </div>
          </div>
        </div>
      </section>
      
      <!-- 模块2：地图展示区 -->
      <section class="map-section">
        <div class="container">
          <div class="section-header" data-aos="fade-up">
            <h2 class="section-title">{{ t('contact.companyLocation') }}</h2>
            <p class="section-desc">{{ t('contact.visitUs') }}</p>
          </div>
          
          <div class="map-container" data-aos="zoom-in">
            <div id="baidu-map" class="baidu-map"></div>
          </div>
        </div>
      </section>
      
      <!-- 模块3：留言板卡片 -->
      <section class="message-form">
        <div class="container">
          <div class="form-card" data-aos="fade-up">
            <div class="form-header">
              <h2 class="form-title">{{ t('contact.leaveMessage') }}</h2>
              <p class="form-desc">{{ t('contact.messageDesc') }}</p>
            </div>
            
            <el-form ref="messageForm" :model="form" :rules="rules" class="contact-form">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="t('contact.name')" prop="name">
                    <el-input v-model="form.name" placeholder="t('contact.enterName')"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="t('contact.phone')" prop="phone">
                    <el-input v-model="form.phone" placeholder="t('contact.enterPhone')"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="t('contact.email')" prop="email">
                    <el-input v-model="form.email" placeholder="t('contact.enterEmail')"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="t('contact.subject')" prop="subject">
                    <el-select v-model="form.subject" placeholder="t('contact.selectSubject')">
                      <el-option label="t('contact.subjectOptions.consult')" value="consult"></el-option>
                      <el-option label="t('contact.subjectOptions.cooperation')" value="cooperation"></el-option>
                      <el-option label="t('contact.subjectOptions.complaint')" value="complaint"></el-option>
                      <el-option label="t('contact.subjectOptions.other')" value="other"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="t('contact.message')" prop="message">
                    <el-input v-model="form.message" type="textarea" :rows="5" placeholder="t('contact.enterMessage')"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item>
                    <el-button type="primary" class="submit-btn" @click="submitForm">{{ t('contact.submitMessage') }}</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
      </section>
    </main>
    
    <!-- 页脚 -->
    <Footer />
    
    <!-- 成功提示弹窗 -->
    <el-dialog v-model="showSuccessDialog" :title="t('common.success')" :width="300" :show-close="false">
      <div class="success-content">
        <div class="success-icon">
          <i class="iconfont icon-success"></i>
        </div>
        <div class="success-text">{{ t('contact.submitSuccess') }}</div>
      </div>
      <template #footer>
        <el-button type="primary" @click="showSuccessDialog = false">{{ t('common.confirm') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, getCurrentInstance } from 'vue'
import { useI18n } from 'vue-i18n'
import $ from 'jquery'
import AOS from 'aos'
import HeaderNav from '@/components/layout/HeaderNav.vue'
import Footer from '@/components/layout/Footer.vue'

// 获取应用实例
const { proxy } = getCurrentInstance()

// 响应式状态
const form = ref({
  name: '',
  phone: '',
  email: '',
  subject: '',
  message: ''
})

const { t } = useI18n();

const rules = ref({
  name: [
    { required: true, message: t('contact.nameRequired'), trigger: 'blur' },
    { min: 2, max: 20, message: t('contact.nameLength'), trigger: 'blur' }
  ],
  phone: [
    { required: true, message: t('contact.phoneRequired'), trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: t('contact.phoneInvalid'), trigger: 'blur' }
  ],
  email: [
    { required: true, message: t('contact.emailRequired'), trigger: 'blur' },
    { type: 'email', message: t('contact.emailInvalid'), trigger: 'blur' }
  ],
  subject: [
    { required: true, message: t('contact.subjectRequired'), trigger: 'change' }
  ],
  message: [
    { required: true, message: t('contact.messageRequired'), trigger: 'blur' },
    { min: 10, max: 500, message: t('contact.messageLength'), trigger: 'blur' }
  ]
})

const showSuccessDialog = ref(false)
const messageForm = ref(null)
let map = null
let marker = null

// 联系信息数据
const contactInfo = [
  {
    icon: 'icon-company',
    title: '公司名称',
    value: '福瑞矿业设备有限公司'
  },
  {
    icon: 'icon-phone',
    title: '销售热线',
    value: '400-888-9999'
  },
  {
    icon: 'icon-address',
    title: '公司地址',
    value: '北京市朝阳区建国路88号福瑞大厦'
  },
  {
    icon: 'icon-fax',
    title: '传真',
    value: '010-88887777'
  },
  {
    icon: 'icon-email',
    title: '邮箱',
    value: 'info@furuimining.com'
  },
  {
    icon: 'icon-worktime',
    title: '工作时间',
    value: '周一至周五 9:00-18:00'
  }
]

// 百度地图初始化
const initBaiduMap = () => {
  // 检查百度地图API是否加载完成
  if (typeof BMapGL === 'undefined') {
    console.error('百度地图API加载失败')
    return
  }
  
  // 创建地图实例
  map = new BMapGL.Map('baidu-map')
  
  // 设置中心点坐标（北京）
  const point = new BMapGL.Point(116.481028, 39.921983)
  
  // 初始化地图，设置中心点坐标和地图级别
  map.centerAndZoom(point, 15)
  
  // 添加地图类型控件
  map.addControl(new BMapGL.MapTypeControl({
    mapTypes: [BMAPGL_NORMAL_MAP, BMAPGL_SATELLITE_MAP]
  }))
  
  // 开启鼠标滚轮缩放
  map.enableScrollWheelZoom(true)
  
  // 添加自定义标记
  const icon = new BMapGL.Icon('@/assets/images/bulding-bg.jpg', new BMapGL.Size(40, 50), {
    anchor: new BMapGL.Size(20, 50) // 设置图标锚点
  })
  
  marker = new BMapGL.Marker(point, { icon: icon })
  map.addOverlay(marker)
  
  // 添加信息窗口
  const infoWindow = new BMapGL.InfoWindow(`
    <div style="padding: 10px;">
      <h3 style="margin-bottom: 5px;">福瑞矿业设备有限公司</h3>
      <p>北京市朝阳区建国路88号福瑞大厦</p>
      <p>电话：400-888-9999</p>
    </div>
  `)
  
  // 点击标记打开信息窗口
  marker.addEventListener('click', function() {
    map.openInfoWindow(infoWindow, point)
  })
  
  // 自动打开信息窗口
  map.openInfoWindow(infoWindow, point)
}

// 加载百度地图API
const loadBaiduMapScript = () => {
  return new Promise((resolve, reject) => {
    // 检查是否已加载
    if (document.getElementById('baidu-map-script')) {
      resolve()
      return
    }
    
    // 创建script标签
    const script = document.createElement('script')
    script.id = 'baidu-map-script'
    script.src = 'https://api.map.baidu.com/api?v=1.0&&type=webgl&ak=您的百度地图AK密钥&callback=initBaiduMap'
    script.type = 'text/javascript'
    script.onerror = reject
    
    // 将初始化函数挂载到window
    window.initBaiduMap = () => {
      resolve()
    }
    
    document.head.appendChild(script)
  })
}

// 提交表单
const submitForm = () => {
  proxy.$refs.messageForm.validate((valid) => {
    if (valid) {
      // 使用jQuery模拟Ajax提交
      $.ajax({
        url: '/api/contact/submit',
        method: 'POST',
        data: form.value,
        dataType: 'json',
        success: function(response) {
          if (response.success) {
            // 显示成功弹窗
            showSuccessDialog.value = true
            
            // 重置表单
            proxy.$refs.messageForm.resetFields()
          } else {
            ElMessage.error(t('contact.submitFailed'))
          }
        },
        error: function() {
          ElMessage.error(t('contact.networkError'))
        }
      })
    }
  })
}

onMounted(() => {
  // 初始化AOS
  AOS.init({
    duration: 1000,
    once: true
  })
  
  // 加载百度地图
  loadBaiduMapScript().then(() => {
    initBaiduMap()
  }).catch(() => {
    console.error('百度地图加载失败')
    // 显示错误信息
    const mapContainer = document.getElementById('baidu-map')
    if (mapContainer) {
      mapContainer.innerHTML = `
        <div class="map-error">
          <i class="iconfont icon-map-error"></i>
          <p>地图加载失败，请刷新页面重试</p>
        </div>
      `
    }
  })
})

onUnmounted(() => {
  // 清除地图实例
  if (map) {
    map.destroy()
    map = null
  }
  
  // 移除百度地图脚本
  const script = document.getElementById('baidu-map-script')
  if (script) {
    document.head.removeChild(script)
  }
  
  // 清除window上的初始化函数
  if (window.initBaiduMap) {
    delete window.initBaiduMap
  }
})
</script>

<style scoped lang="scss">
.contact-page {
  // 公司联系方式
  .contact-info {
    padding: 60px 0;
    
    .info-cards {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;
      
      @media (max-width: 991px) {
        grid-template-columns: repeat(2, 1fr);
      }
      
      @media (max-width: 575px) {
        grid-template-columns: 1fr;
      }
      
      .info-card {
        display: flex;
        padding: 25px;
        background-color: #f9f9f9;
        border-radius: 8px;
        transition: transform 0.3s ease;
        
        &:hover {
          transform: translateY(-5px);
        }
        
        .info-icon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          background-color: rgba(216, 49, 91, 0.1);
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;
          flex-shrink: 0;
          
          .iconfont {
            font-size: 24px;
            color: #D8315B;
          }
        }
        
        .info-content {
          .info-title {
            font-size: 0.95rem;
            color: #666;
            margin-bottom: 5px;
          }
          
          .info-value {
            font-size: 1.1rem;
            font-weight: 500;
            color: #333;
          }
        }
      }
    }
  }
  
  // 地图展示区
  .map-section {
    padding: 60px 0;
    background-color: #f9f9f9;
    
    .section-header {
      text-align: center;
      margin-bottom: 30px;
      
      .section-title {
        font-size: 2rem;
        color: #0A2463;
        margin-bottom: 10px;
      }
      
      .section-desc {
        color: #666;
      }
    }
    
    .map-container {
      height: 500px;
      
      .baidu-map {
        width: 100%;
        height: 100%;
        border-radius: 8px;
        overflow: hidden;
      }
      
      .map-error {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background-color: #ffffff;
        border-radius: 8px;
        
        .iconfont {
          font-size: 40px;
          color: #e0e0e0;
          margin-bottom: 15px;
        }
        
        p {
          color: #999;
        }
      }
    }
  }
  
  // 留言板卡片
  .message-form {
    padding: 60px 0;
    
    .form-card {
      background-color: #ffffff;
      border-radius: 8px;
      box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
      overflow: hidden;
      
      .form-header {
        padding: 30px;
        background: linear-gradient(135deg, #0A2463 0%, #3E92CC 100%);
        color: #ffffff;
        
        .form-title {
          font-size: 1.8rem;
          margin-bottom: 10px;
        }
        
        .form-desc {
          opacity: 0.9;
          max-width: 600px;
        }
      }
      
      .contact-form {
        padding: 30px;
        
        .el-row {
          margin-bottom: 10px;
        }
        
        .el-form-item {
          margin-bottom: 20px;
        }
        
        .submit-btn {
          padding: 12px 30px;
          font-size: 16px;
          background-color: #D8315B;
          border-color: #D8315B;
          
          &:hover {
            background-color: #b92a4c;
            border-color: #b92a4c;
          }
        }
      }
    }
    
    // 成功提示弹窗
    .success-content {
      text-align: center;
      padding: 20px 0;
      
      .success-icon {
        font-size: 60px;
        color: #4CAF50;
        margin-bottom: 15px;
      }
      
      .success-text {
        font-size: 1.1rem;
        color: #333;
      }
    }
  }
}
</style>